<template>
  <view class="container">
    <button @click="initBluetooth">初始化蓝牙</button>
    <button @click="startDiscovery">搜索设备</button>
    <button @click="stopDiscovery">停止搜索</button>
    
    <view class="device-list">
      <view 
        v-for="device in devices" 
        :key="device.deviceId"
        @click="connectDevice(device.deviceId)"
      >
        <text>{{ device.name || '未知设备' }}</text>
        <text class="device-id">{{ device.deviceId }}</text>
      </view>
    </view>
    
    <view class="print-area">
      <textarea v-model="printContent" placeholder="输入打印内容"></textarea>
      <button @click="printText">打印文本</button>
      <button @click="printTestPage">打印测试页</button>
      
      <!-- 汉印专用功能 -->
      <view class="hanprint-section">
        <text class="section-title">汉印专用功能</text>
        <button @click="printCenterText(printContent)">居中打印</button>
        <button @click="printBarcode('12345678', '128')">打印条码</button>
        <button @click="printWithCount(printContent, 3)">打印3份</button>
        <button @click="printHanprintDemo">综合测试</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

// 响应式变量
const devices = ref([]) // 蓝牙设备列表
const connected = ref(false) // 连接状态
const connectedDeviceId = ref('') // 已连接设备ID
const printContent = ref('测试打印内容\n这是第二行') // 打印内容
const bluetoothEnabled = ref(false) // 蓝牙是否开启
const writeCharId = ref('') // 可写特征值UUID
const serviceId = ref('') // 服务ID

// 初始化蓝牙适配器
const initBluetooth = () => {
  uni.openBluetoothAdapter({
    success: (res) => {
      console.log('蓝牙初始化成功', res)
      getBluetoothAdapterState()
      // 监听蓝牙状态变化
      uni.onBluetoothAdapterStateChange(handleBluetoothStateChange)
      // 监听发现新设备
      uni.onBluetoothDeviceFound(handleDeviceFound)
    },
    fail: (err) => {
      console.error('蓝牙初始化失败', err)
      uni.showToast({
        title: '请开启蓝牙',
        icon: 'none'
      })
    }
  })
}

// 获取蓝牙适配器状态
const getBluetoothAdapterState = () => {
  uni.getBluetoothAdapterState({
    success: (res) => {
      console.log('蓝牙状态', res)
      bluetoothEnabled.value = res.available
      if (!res.available) {
        uni.showToast({
          title: '蓝牙不可用',
          icon: 'none'
        })
      }
    }
  })
}

// 处理蓝牙状态变化
const handleBluetoothStateChange = (state) => {
  console.log('蓝牙状态变化', state)
  bluetoothEnabled.value = state.available
}

// 开始搜索设备
const startDiscovery = () => {
  if (!bluetoothEnabled.value) {
    uni.showToast({ title: '蓝牙未开启', icon: 'none' })
    return
  }
  
  devices.value = []
  uni.startBluetoothDevicesDiscovery({
    services: [], // 经典蓝牙不需要指定服务UUID
    allowDuplicatesKey: false,
    success: (res) => {
      console.log('开始搜索设备', res)
      uni.showToast({ title: '开始搜索设备', icon: 'none' })
    },
    fail: (err) => {
      console.error('搜索设备失败', err)
    }
  })
}

// 停止搜索设备
const stopDiscovery = () => {
  uni.stopBluetoothDevicesDiscovery({
    success: (res) => {
      console.log('停止搜索设备', res)
    }
  })
}

// 处理发现的设备
const handleDeviceFound = (devices) => {
  const newDevice = devices.devices[0]
  // 过滤重复设备和名称为空的设备
  if (newDevice.name && !devices.value.some(d => d.deviceId === newDevice.deviceId)) {
    devices.value.push(newDevice)
  }
}

// 连接设备
const connectDevice = (deviceId) => {
  stopDiscovery()
  uni.createBLEConnection({
    deviceId,
    success: (res) => {
      console.log('连接成功', res)
      connected.value = true
      connectedDeviceId.value = deviceId
      uni.showToast({ title: '连接成功' })
      
      // 获取服务列表（经典蓝牙可能不需要）
      getBLEDeviceServices(deviceId)
    },
    fail: (err) => {
      console.error('连接失败', err)
      uni.showToast({ title: '连接失败', icon: 'none' })
    }
  })
}

// 获取设备服务
const getBLEDeviceServices = (deviceId) => {
  uni.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      console.log('设备服务', res.services)
      // 找到通信服务
      const service = res.services[0]
      if (service) {
        getBLEDeviceCharacteristics(deviceId, service.uuid)
      }
    }
  })
}

// 获取特征值
const getBLEDeviceCharacteristics = (deviceId, serviceId) => {
  uni.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
      console.log('特征值', res.characteristics)
      // 保存可写特征值UUID用于后续通信
      for (let char of res.characteristics) {
        if (char.properties.write) {
          writeCharId.value = char.uuid
          serviceId.value = serviceId
          break
        }
      }
    }
  })
}

// 发送打印指令
const sendPrintData = (data) => {
  if (!connected.value || !writeCharId.value) {
    uni.showToast({ title: '请先连接设备', icon: 'none' })
    return
  }
  
  // 将数据转换为ArrayBuffer
  const buffer = new Uint8Array(data).buffer
  
  uni.writeBLECharacteristicValue({
    deviceId: connectedDeviceId.value,
    serviceId: serviceId.value,
    characteristicId: writeCharId.value,
    value: buffer,
    success: (res) => {
      console.log('发送成功', res)
    },
    fail: (err) => {
      console.error('发送失败', err)
      uni.showToast({ title: '发送失败', icon: 'none' })
    }
  })
}

// 打印文本（汉印格式）
const printText = () => {
  if (!printContent.value) return
  
  // 汉印打印机使用文本命令格式
  let printCommand = ''
  
  // 添加文本内容
  printCommand += printContent.value + '\n'
  
  // 走纸命令
  printCommand += 'PRINT\n'
  
  // 转换为字节数组发送
  const encoder = new TextEncoder()
  const data = encoder.encode(printCommand)
  sendPrintData(Array.from(data)) // 将字节数组转为普通数组
}

// 汉印专用：打印条码
const printBarcode = (barcodeValue, barcodeType = '128') => {
  let printCommand = ''
  
  // 条码命令格式：BARCODE 128 1 1 50 1 30 barcodeValue
  printCommand += `BARCODE ${barcodeType} 1 1 50 1 30 ${barcodeValue}\n`
  printCommand += 'PRINT\n'
  
  const encoder = new TextEncoder()
//   encode 方法：实现utf8编码转为字节流。输入：文本；输出：Unit8Array
  const data = encoder.encode(printCommand)
  sendPrintData(Array.from(data))
}

// 汉印专用：居中打印文本
const printCenterText = (text) => {
  let printCommand = ''
  
  // 居中命令
  printCommand += 'CENTER\n'
  printCommand += text + '\n'
  printCommand += 'PRINT\n'
  
  const encoder = new TextEncoder()
  const data = encoder.encode(printCommand)
  sendPrintData(Array.from(data))
}

// 汉印专用：设置打印份数
const printWithCount = (text, count = 1) => {
  let printCommand = ''
  
  // COUNT命令设置打印份数
  printCommand += `COUNT ${count}\n`
  printCommand += text + '\n'
  printCommand += 'PRINT\n'
  
  const encoder = new TextEncoder()
  const data = encoder.encode(printCommand)
  sendPrintData(Array.from(data))
}

// 打印测试页（汉印格式）
const printTestPage = () => {
  let printCommand = ''
  
  // 测试页内容
  printCommand += 'CENTER\n'  // 居中
  printCommand += 'TESTING 001\n'  // 标题
  printCommand += '\n'  // 空行
  
  // 添加条码
  printCommand += 'BARCODE 128 1 1 50 1 30 12345678\n'
  printCommand += '\n'
  
  // 添加文本
  printCommand += 'TEXT 0 0 50 TESTING 001\n'
  printCommand += '\n'
  
  // 设置打印3份
  printCommand += 'COUNT 3\n'
  printCommand += 'Print 3 labels\n'
  
  // 执行打印
  printCommand += 'PRINT\n'
  
  const encoder = new TextEncoder()
  const data = encoder.encode(printCommand)
  sendPrintData(Array.from(data))
}

// 汉印专用：综合测试打印
const printHanprintDemo = () => {
  let printCommand = ''
  
  // 居中标题
  printCommand += 'CENTER\n'
  printCommand += '汉印打印机测试\n'
  printCommand += '\n'
  
  // 普通文本
  printCommand += 'TEXT 0 0 50 TESTING 001\n'
  printCommand += 'TEXT 0 0 100 Barcode Value is 12345678\n'
  printCommand += '\n'
  
  // 条码（128码）
  printCommand += 'BARCODE 128 1 1 50 1 30 12345678\n'
  printCommand += '\n'
  
  // 设置打印份数
  printCommand += 'COUNT 1\n'
  
  // 表单样式
  printCommand += 'FORM\n'
  printCommand += 'PRINT\n'
  
  const encoder = new TextEncoder()
  const data = encoder.encode(printCommand)
  sendPrintData(Array.from(data))
}

// 关闭蓝牙适配器
const closeBluetoothAdapter = () => {
  uni.closeBluetoothAdapter({
    success: (res) => {
      console.log('关闭蓝牙适配器', res)
    }
  })
}


</script>

<style scoped>
.container {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.device-list {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 10px;
  margin-top: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.device-list > view {
  padding: 10px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.device-id {
  font-size: 12px;
  color: #666;
  display: block;
}

.print-area {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

textarea {
  height: 120px;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 10px;
}

.hanprint-section {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  display: block;
}

.hanprint-section button {
  margin: 5px;
  padding: 8px 16px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}

.hanprint-section button:active {
  background-color: #0056cc;
}
</style>